const fs = require('fs')
// var proto = Object.getOwnPropertyNames(global)
//shift + option + A
/* console.log(proto)
console.log(process.argv)
process.stdin.pipe(process.stdout)
process.stdin.setEncoding('utf-8')
process.stdin.on('readable',() => {
    const thunk = process.stdin.read()
    // if(thunk !== null)
    process.stdout.write('data'+ thunk)
})   */

/* 
利用rs.open,read, write，Buffer 实现文件拷贝
*/
/* 
const buf = Buffer.alloc(10)
const BUFFER_SIZE = buf.length
let readOffset = 0

fs.open('5.1.Md', 'r', (err, rfd) => {
    fs.open('copy.txt', 'w', (err, wfd) => {
        function next(){
            fs.read(rfd, buf, 0, BUFFER_SIZE, readOffset, (err, readBytes) => {
                if(!readBytes){
                    fs.close(rfd)
                    fs.close(wfd)
                    return
                }
                readOffset += readBytes
                fs.write(wfd, buf, 0, readBytes, (err, written) => {
                    next()                    
                })
            })
        }
        next()
    })
}) */
// console.log(process) 

//同步洋葱模型  1->2->3->3->2->1
function syncCompose( milldeware ) {
    return () => {
        //核心
        const dispatch = index => {
            if(index >= middleware.length) return 
            const fn = milldeware[index]
            fn({}, () => dispatch[index ++])
        }   
        return dispatch(0)
    }
}

//异步递归调用中间件处理函数  洋葱模型 
function compose( milldeware ) {
    return () => {
        //核心
        const dispatch = index => {
            if(index >= middleware.length) return Promise.resolve()
            const fn = milldeware[index]
            /* 
            * 为了实现异步函数的洋葱模型 需要等待当前异步dispacth执行完成才能执行next()后的代码
            * 为了能在dispach前使用await 需要返回Promise
            */
            return Promise.resolve(fn({}, () => dispatch[index ++])) 
        }   
        return dispatch(0)
    }
}